<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'interfaces/i_db_storable.class.php');


require_once('visitor_language.class.php');


class Visitor_Language_DBC extends Visitor_Language implements I_DB_Storable {
	public function save(DB_Connection $dbc) {
		$ret = false;

		if ($this->get_id()) {
			$ret = $this->update($dbc);
		} else {
			$ret = $this->insert($dbc);
			$this->set_id($ret);
		}

		return $ret;
	}


	public function load_by_id(DB_Connection $dbc, $id) {
		tangra_if_not_int_throw_e($id);


		$ret = false;

		$sql = "select visitor, language from visitors_languages where id = $id";
		$rez = $dbc->execute($sql);

		if (!$rez->is_eof()) {
			$rez_obj = $rez->fetch_object();

			$this->set_id($id);
			$this->set_visitor($rez_obj->VISITOR);
			$this->set_language($rez_obj->LANGUAGE);

			$ret = $id;
		}


		return $ret;
	}


	protected function insert(DB_Connection $dbc) {
		$ret = false;

		$id = $dbc->generate_id('visitors_languages_seq');
		$visitor = $this->get_visitor();
		$language = $this->get_language();

		if ($id) {
			$sql = "insert into visitors_languages (id, ".
									      "visitor, ".
									      "language ".
									      ") ".
								"values ".
									      "($id,".
									      "$visitor, ".
									      "$language ".
									      ")";
			$dbc->execute($sql);
			$ret = $id;
		} else {
			throw new TE_Exception('visitors_languages_seq');
		}

		return $ret;
	}


	protected function update(DB_Connection $dbc) {
		$id = $this->get_id();
		$language = $this->get_language();

		$sql = "update visitors_languages set ".
						"language = $language ".
					"where id = ".$id;

		$dbc->execute($sql);
		$ret = $id;

		return $ret;
	}


	public function load_by_visitor_id(DB_Connection $dbc, $visitor_id) {
		tangra_if_not_int_throw_e($visitor_id);

		$ret = false;
		$sql = "select id, language from visitors_languages where visitor = $visitor_id";

		$rez = $dbc->execute($sql);

		if (!$rez->is_eof()) {
			$rez_obj = $rez->fetch_object();

			$this->set_id($rez_obj->ID);
			$this->set_visitor($visitor_id);
			$this->set_language($rez_obj->LANGUAGE);

			$ret = $rez_obj->ID;
		}

		return $ret;
	}
}